import router from "@src/router";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import reservation from "@src/store/reservation";
import {
  getAppointmentPlanList,
  getAppointmentResourcesDetail,
  getAppointmentShopDetail,
  getGoodsList,
} from "@src/api/reservation";
import { OPEN_STATE } from "@src/common/reservation/constant/index.js";
import location from "@src/store/location";
import { debounce, throttle } from "@src/common/utils";
import base from "@src/store/base";
Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["themeColor", "themeTitleColor", "perms", "businessName"],
    },
    {
      store: reservation,
      fields: ["resourcesDetail", "goodsInfo"],
      actions: ["setResourcesDetail", "setSubmitGoodsInfo"],
    },
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation", "showAuthTip"],
    },
  ],
  data: {
    loading: false,
    hasNextPage: true,
    refresherEnabled: true,
    //----搜索框start---
    isInputFocus: false,
    inputValue: "",
    OPEN_STATE,
    //----搜索框end---
    //----列表start---
    params: {
      pageSize: 10,
      pageNum: 1,
      name: "",
    },
    list: [],
    //----列表end----
    //---- 时间选择器start----
    isShowDateSelect: false,
    categoryId: null,
    planId: null,
    //---- 时间选择器end----
    //信息
    options: {},
    //资源信息
    categoryInfo: {},
    //时间
    dateTimeInfo: {},
    //商品信息
    goodInfo: {},
    //商品选择器
    isShowGoodSelect: false,
    skuId: 0,
    originOffsetY: 0,
    specTitle: [],
    categoryList: [],
    goodsData: {},
    planInfo: {},
  },
  onLoad: function (options) {
    console.log(options);
    this.setData({
      options,
    });
  },
  onPullDownRefresh() {
    this.onRefresher();
  },
  onReady() {
    wx.showLoading({ title: "加载中" });
    if (this.data.resourcesDetail) {
      const info = JSON.parse(this.data.resourcesDetail);
      console.log("资源详情", info);
      this.setData({
        categoryInfo: info,
        params: {
          ...this.data.params,
          appointmentCategoryId: info.id,
          shopId: this.options.shopId,
        },
        categoryId: info.id,
      });
    }
    // this.fetchData();
  },

  onLogin() {
    this.getLocation(true)
      .then((res) => {
        if (this.data.options.shopId) {
          this.setData({ loading: true });
          this.setData({ latitude: res.latitude, longitude: res.longitude });
          this.fetchData();
        }
      })
      .catch((res) => {
        this.setData({ loading: true });
        if (this.data.options.shopId) {
          this.fetchData();
        }
      });
  },
  async fetchData() {
    const {
      options: { shopId, id },
      latitude = "",
      longitude = "",
      categoryId,
      params: { appointmentCategoryId },
    } = this.data;
    //获取门店信息
    const { code, data } = await getAppointmentShopDetail({
      shopId,
      latitude: latitude || "",
      longitude: longitude || "",
    });
    if (code === 0) {
      data.distance = (data.shopInfoResp.distance / 1000).toFixed(2);
      this.setData({
        shopInfo: data,
      });
      await this.getList(true);
    }
    if (appointmentCategoryId || categoryId) {
      const { code: detailCode, data: detailData } =
        await getAppointmentResourcesDetail({
          categoryId: appointmentCategoryId || categoryId,
        });
      if (detailCode === 0) {
        const labels = detailData.label.split(";");
        const tags = [];
        labels.map((vc) => {
          if (vc) {
            tags.push(vc);
          }
        });
        detailData.labels = tags;
        this.setData({
          categoryInfo: detailData,
          params: {
            ...this.data.params,
            appointmentCategoryId: detailData.id,
            shopId: this.options.shopId,
          },
          categoryId: detailData.id,
        });
        console.log("请求的资源详情", detailData);
      }
    }
  },

  async getList(isClear = false) {
    if (isClear) {
      this.setData({
        params: {
          ...this.data.params,
          pageSize: 10,
          pageNum: 1,
        },
      });
    }
    const { code, data } = await getAppointmentPlanList(this.data.params);
    if (code === 0) {
      this.setData({ loading: false });
      // this.setData({ refresherEnabled: false });
      wx.hideLoading();
      wx.stopPullDownRefresh();
      const { list, hasNextPage } = data;
      this.setData({
        hasNextPage,
        list: isClear ? list : [...this.data.list, ...list],
        refresherEnabled: true,
      });
    }
  },

  //----搜索框start---
  onRefresher() {
    this.setData({ loading: true });
    wx.showLoading({ title: "加载中" });
    this.fetchData();
  },
  inputFocus() {
    this.setData({ isInputFocus: true });
  },
  inputBlur() {
    this.setData({ isInputFocus: false });
    this.fetchData();
    // this.queryNearbyShopListReq();
  },
  bindKeyInput: function (e) {
    this.setData({
      params: {
        ...this.data.params,
        name: e.detail.value,
      },
    });
    debounce(() => {
      this.setData({
        isInputFocus: false,
      });
      this.getList(true);
    }, 500)();
  },
  //----搜索框end----
  //----列表start---
  onScrollToLower() {
    const pageNum = this.data.params.pageNum + 1;
    this.setData({
      params: {
        ...this.data.params,
        pageSize: 10,
        pageNum,
      },
    });
    this.getList(false);
  },
  handleToResources(e) {
    console.log(e);
    const { shopConfigId } = this.data.shopInfo.shopInfoResp;
    const {
      currentTarget: {
        dataset: { item },
      },
    } = e;
    item.imgUrl = item.imageList[0];
    this.setData({
      goodInfo: item,
      planId: item.id,
    });
    getGoodsList({
      goodsSerial: item.goodsSerial,
      shopConfigId,
      planId: item.id,
    }).then((res) => {
      const { code, data } = res;
      if (code === 0) {
        const { goodsPageData, categoryList, planInfo } = data;
        //初始化操作
        const skuInfo = goodsPageData.skuInfo.skuList[0];
        const specInfo = goodsPageData.skuInfo.specList[0];
        this.setData({
          categoryList,
          goodsData: goodsPageData,
          planInfo,
          skuId: skuInfo.skuId,
          categoryId: categoryList.length > 0 ? categoryList[0].id : 0,
          planId: planInfo.planId || 0,
          specTitle: `${specInfo?.attrList[0]?.title || ""}`,
        });
        console.log("初始化", categoryList);
        const showSelect = goodsPageData.skuInfo.specList.length > 0;
        this.setData({
          isShowDateSelect: !showSelect,
          isShowGoodSelect: showSelect,
        });
      }
    });
  },
  //商品选择器
  handleShowSelectGood() {
    this.setData({
      isShowGoodSelect: !this.data.isShowGoodSelect,
    });
  },
  handleSelectCategory(e) {
    const {
      detail: { planId, id },
    } = e;
    this.setData({
      categoryId: id,
      planId,
    });
    console.log("商品选择器", id);
  },
  handleSelectGoods(e) {
    console.log("handleSelectGoods", e);
    const {
      detail: { skuId },
    } = e;
    if (skuId > 0) {
      this.setData({
        skuId,
      });
    }
    if (this.data.skuId === null || this.data.skuId === undefined) {
      wx.showModal({
        content: "请选择方案",
        showCancel: false,
      });
      return;
    }
    this.setData({
      isShowGoodSelect: false,
      isShowDateSelect: true,
    });
  },
  //时间选择
  handleClose() {
    this.setData({
      isShowDateSelect: false,
    });
  },

  handleBeginDayChange(e) {
    console.log("handleBeginDayChange", e);
  },
  handleSelect(e) {
    const { detail } = e;
    this.setData({
      dateTimeInfo: detail,
    });
    console.log("选择了时间", e);
  },
  handleConfirmSelect() {
    // 预约时间，套餐信息，sku信息
    const { categoryInfo, dateTimeInfo, goodInfo, skuId, goodsData } =
      JSON.parse(JSON.stringify(this.data));
    const {
      skuInfo: { skuList, specList },
    } = goodsData;
    categoryInfo.planId = goodInfo.id;
    //sku信息
    const skuInfo = skuList.filter((v) => v.skuId === skuId)[0];
    //spec套餐信息
    const specAttrs = skuInfo?.specAttrs;
    console.log("spec套餐信息", skuId, skuInfo, specAttrs);
    let specs = [];
    specList.forEach((spItem) => {
      if (spItem.attrList.length > 0) {
        spItem.attrList.forEach((v) => {
          if (specAttrs.includes(v.id)) {
            specs.push(v);
          }
        });
      }
    });
    //预约时间
    const info = {
      categoryInfo,
      skuInfo: {},
      dateTimeInfo,
      specs,
    };
    info.skuInfo = {
      ...goodInfo,
      ...goodsData.goods,
      ...skuInfo,
      id: goodsData.goodsId,
      imgUrl: goodsData.goods.imgList[0],
    };
    if (
      dateTimeInfo.time === null ||
      dateTimeInfo.time === undefined ||
      dateTimeInfo.time.num === null ||
      dateTimeInfo.time.num === undefined ||
      dateTimeInfo.time.num <= 0 ||
      categoryInfo.id === null ||
      categoryInfo.id === undefined ||
      goodInfo.price === null ||
      goodInfo.price === undefined ||
      skuInfo.skuId === null ||
      skuInfo.skuId === undefined ||
      skuInfo.price === null ||
      skuInfo.price === undefined
    )
      return;
    //特殊处理
    info.skuInfo.id = goodInfo.productId;
    categoryInfo.serviceDuration = goodInfo.serviceDuration;
    console.log("提交", skuInfo);
    this.setSubmitGoodsInfo(JSON.stringify(info)).then(() => {
      wx.showLoading({
        title: "保存信息中",
      });
      setTimeout(() => {
        wx.hideLoading();
        router.push({
          name: "reservation/submit_reservation",
          params: {
            title: 0,
            shopId: this.data.shopInfo.shopInfoResp.shopId,
            // navIndex: e.currentTarget.dataset.index,
          },
        });
      }, 500);
    });
  },
  //----列表end----
  handleToProject(e) {
    const {
      currentTarget: {
        dataset: { item },
      },
    } = e;
    const { shopId, shopConfigId } = this.data.options;

    router.push({
      name: `reservation/project_detail`,
      params: {
        id: item.id,
        planId: item.id,
        shopId,
        shopConfigId,
        goodsSerial: item.goodsSerial,
      },
    });
  },
});
